
import React, { useState, useEffect, useContext, createContext } from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import Accordion from 'react-bootstrap/Accordion';
import { useAccordionButton } from 'react-bootstrap/AccordionButton';
import Card from 'react-bootstrap/Card';
import Highlight from 'react-highlight';


import "highlight.js/styles/a11y-light.css";
import "./DialogLarge.css"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faAngleRight } from '@fortawesome/free-solid-svg-icons';
import { faAngleDown } from '@fortawesome/free-solid-svg-icons';


const ActiveIdContext = createContext();

function CustomToggle({ children, eventKey }) {
    const [activeId, setActiveId] = useContext(ActiveIdContext);
    const decoratedOnClick = useAccordionButton(
        eventKey, () => { (eventKey === activeId) ? setActiveId(-1) : setActiveId(eventKey); });
    return (
        <div className={(eventKey === activeId) ?'DialogLargeAccHeaderActive':'DialogLargeAccHeader'} onClick={decoratedOnClick}>
            {children}
            <div style={{ position: 'absolute', top: '10px', right: '10px' }}>
                {(eventKey === activeId) ? <FontAwesomeIcon icon={faAngleDown} color="#489FD3" /> : <FontAwesomeIcon icon={faAngleRight} color="#EAEAEA" />}
            </div>

        </div>
    )
}


//我的产品分类displayid
const LD_MyProductCat1DisplayId = "myproduct";
const LD_MyScriptCat2DisplayId = "myscript";

//搜索分类
const LD_SearchDisplayId = "search";

// props.isOpen
// props.onClose
// props.loginedUser
// props.onProductCheckChanged ( pdtinfo , isChecked )
// props.groupA 
// props.groupB 
// props.isActiveGroupA
function DialogLarge(props) {

    const [activeLevel1Index, setActiveLevel1Index] = useState(-1);
    const [activeProductDisplay, setActiveProductDisplay] = useState({ dpid: 0 });
    const [detailHtmlText, setDetailHtmlText] = useState("");
    const [detailScriptText, setDetailScriptText] = useState("");
    const [cateData, setCateData] = useState(null);
    const [searchText, setSearchText] = useState("");
    const [currGroup, setCurrGroup] = useState([]);

    const [activeId, setActiveId] = useState(0);

    useEffect(() => {
        if (props.isActiveGroupA) {
            setCurrGroup(props.groupA);
        } else {
            setCurrGroup(props.groupB);
        }
    }, [props.isActiveGroupA, props.groupA, props.groupB])



    const isProductInCurrGroup = function (displayid1) {
        for (const iterator of currGroup) {
            if (iterator.displayid === displayid1) {
                return true;
            }
        }
        return false;
    }



    const httpGetCateData = function () {
        const url = global.g_serverAPIRoot + "product/categories2?uid=" + props.loginedUser.uid;
        fetch(url)
            .then((response) => response.json())
            .then((result) => {
                if (result.state === 0) {
                    setCateData(result.data);
                    setActiveLevel1Index(0);
                } else {
                    console.log("error:" + result.message);
                }
            })
            .catch(err => {
                console.log(err);// 505 404 ... errors
            });
    }

    const onLevel1TabClick = function (level1index) {
        setActiveLevel1Index(level1index);
        setActiveProductDisplay({ dpid: 0,type:'none' });
    }

    const onProductCellClick = function (pdtobj) {
        setActiveProductDisplay(pdtobj.productDisplay);
    }


    const onClose = function () {
        props.onClose();
    }


    const httpGetAndSetScriptTextDetailView = function (scriptid) {
        let url1 = global.g_serverAPIRoot + "scripts/content/?sid=" + scriptid + "&utime=" + Date.now();
        fetch(url1)  //GET
            .then(response => response.json())
            .then(result => {
                setDetailScriptText(result.data);
                setDetailHtmlText("");
            }).catch(err => {
                console.log(err);// 505 404 ... errors
                setDetailScriptText("");
                setDetailHtmlText("<h3 style=\"color:#888\" >获取脚本信息失败</h3>");
            });
    }

    const httpGetDetailHtml = function (displayObj) {
        if (displayObj.type === 'us') {
            //获取脚本
            let scriptid1 =
                httpGetAndSetScriptTextDetailView(displayObj.dpid);
        } else {
            //产品信息 html
            if (displayObj.dpid === 0) return;
            let url = global.g_staticResourceRoot + 'docs/pdtdetail-' + displayObj.dpid + '.html';
            fetch(url)
                .then((response) => response.text())
                .then((result) => {
                    setDetailScriptText("");
                    setDetailHtmlText(result);
                })
                .catch(err => {
                    setDetailScriptText("");
                    setDetailHtmlText("<h3 style=\"color:#888\" >获取描述信息失败</h3>");
                });
        }
    }


    useEffect(() => {
        setDetailScriptText("");
        setDetailHtmlText("");
        if (activeProductDisplay !== null) {
            httpGetDetailHtml(activeProductDisplay);
        } else {
            setDetailScriptText("");
            setDetailHtmlText("<h3 style=\"color:#888\" >没有描述信息</h3>");
        }
    }, [activeProductDisplay])


    //从服务器加载用户脚本，然后更新categories状态，UI更新交给React内部机制
    //2022-8-11
    const httpUpdateUserScripts =function() {
        const api = global.g_serverAPIRoot + 'product/userscripts?uid='+props.loginedUser.uid ;
        fetch(api)
        .then((response) => response.json())
        .then((result) => {
            if( typeof result.data !=='undefined' ){
                setUserScriptIntoCateData(cateData,result.data) ;
            }
        })
        .catch(err => {
            
        });
    }



    //设置我的脚本到cateData中
    const setUserScriptIntoCateData = function (oldCateData, scriptdata) {
        for (let i = 0; i < oldCateData.level1Array.length; ++i) {
            if (oldCateData.level1Array[i].displayid === LD_MyProductCat1DisplayId) {
                for (let j = 0; j < oldCateData.level1Array[i].level2Array.length; ++j) {
                    if (oldCateData.level1Array[i].level2Array[j].displayid === LD_MyScriptCat2DisplayId) {
                        let newCateDataWithMyScripts = { ...oldCateData };
                        newCateDataWithMyScripts.level1Array[i].level2Array[j].productArray = scriptdata;
                        setCateData(newCateDataWithMyScripts);
                        return;
                    }
                }
            }
        }
    }

    useEffect(() => {
        if (props.isOpen === true) {
            setActiveProductDisplay({ dpid: 0,type:'none' });
            setDetailHtmlText("");
            httpGetCateData();
        }
    }, [props.isOpen])



    const setSearchProductsIntoCateData = function (pdtarr) {
        for (let i = 0; i < cateData.level1Array.length; ++i) {
            if (cateData.level1Array[i].displayid === LD_SearchDisplayId) {
                for (let j = 0; j < cateData.level1Array[i].level2Array.length; ++j) {
                    if (cateData.level1Array[i].level2Array[j].displayid === LD_SearchDisplayId) {
                        let newCateDataWithMyScripts = { ...cateData };
                        newCateDataWithMyScripts.level1Array[i].level2Array[j].productArray = pdtarr;
                        setCateData(newCateDataWithMyScripts);
                        return;
                    }
                }
            }
        }
    }


    const httpSearchProducts = function (keystr) {
        //http://192.168.56.103:15900/pe/product/search?key=NDVI&uid=0
        const api = global.g_serverAPIRoot + 'product/search?key=' + keystr + "&uid=" + props.loginedUser.uid;
        fetch(api)
            .then((response) => response.json())
            .then((result) => {
                if (result.state === 0) {
                    setSearchProductsIntoCateData(result.data);
                } else {
                    console.log("error:" + result.message);
                }
            })
            .catch(err => {
                console.log(err);// 505 404 ... errors
            });
    }

    const onSearchTextChanged = function (ev) {
        setSearchText(ev.target.value);
        let key2 = ev.target.value.trim();
        if (key2 !== '') {
            httpSearchProducts(key2);
        } else {
            setSearchProductsIntoCateData([]);
        }
    }

    const onSearchInputFocus = function () {
        for (let i = 0; i < cateData.level1Array.length; ++i) {
            if (cateData.level1Array[i].displayid === LD_SearchDisplayId) {
                setActiveLevel1Index(i);
                setActiveProductDisplay({ dpid: 0,type:'none' });
                return;
            }
        }
    }

    const onCheckBoxChanged = function (ev, pdtitem) {
        //ev.target.checked
        const ischecked = ev.target.checked;
        props.onProductCheckChanged(pdtitem, ischecked);

    }


    //点击新建脚本按钮2022-5-10
    const onNewScriptClicked = function() {
        const formData = new FormData();
        formData.append('uid' , props.loginedUser.uid) ;
        formData.append('script', "function main(){return null;}"); 
        const url = global.g_serverAPIRoot + "scripts/new2"
        fetch(
            url,
            {
                method: 'POST',
                body: formData,
            }
        )
        .then((response) => response.json())
        .then((result) => {
            if( result.state===0 ){
                //good
                httpUpdateUserScripts() ;
            }else{
                //bad
            }
        }).catch(err=> {
            console.log(err) ;// 505 404 ... errors
        }) ;
    }


    //用户脚本单元格删除
    const onDeleteUserScriptClick = function(displayObj) {
        const formData = new FormData();
        formData.append('sid' ,displayObj.pid) ;//use pid for sid in user-script product.productDisplay
        const url = global.g_serverAPIRoot + "scripts/delete"
        fetch(
            url,
            {
                method: 'POST',
                body: formData,
            }
        )
        .then((response) => response.json())
        .then((result) => {
            if( result.state===0 ){
                //good
                httpUpdateUserScripts() ;
            }else{
                //bad
            }
        }).catch(err=> {
            console.log(err) ;// 505 404 ... errors
        }) ;
    }

    return (
        <Modal
            show={props.isOpen}
            dialogClassName="DialogLarge"
        >
            <Modal.Body className='DialogLargeModelBody' >
                {/* Header */}
                <div className='DialogLargeHeader'>
                    <input type="search" className="form-control"
                        style={{ width: '1120px', display: 'inline-block' }}
                        value={searchText}
                        onChange={onSearchTextChanged}
                        onFocus={onSearchInputFocus}
                        placeholder="搜索"
                    />
                    <div className='DialogLargeClose' onClick={onClose}>
                        ×
                    </div>
                </div>


                {/* TABs */}
                <div className='DialogLargeTabContainer'>
                    {
                        (typeof cateData !== 'undefined' && cateData !== null) ? (
                            cateData.level1Array.map((item, index) => {
                                let clsname = "DialogLargeTab";
                                if (index === activeLevel1Index) clsname = "DialogLargeTab Active";
                                return <div className={clsname} key={"key" + index}
                                    onClick={() => { onLevel1TabClick(index) }}>{item.meta.metavalstr}</div>;
                            }
                            )
                        ) : ""
                    }
                </div>


                {/* Body */}
                <div className='DialogLargeBody'>
                    <div className='DialogLargeListView'>
                        {
                            (activeLevel1Index>=0 && cateData.level1Array[activeLevel1Index].displayid === LD_MyProductCat1DisplayId) ? (
                                <div className="d-grid gap-2">
                                    <Button 
                                    variant="success" size="sm" onClick={onNewScriptClicked}>
                                        新建脚本
                                    </Button>
                                </div>
                            ) : ("")
                        }
                        <ActiveIdContext.Provider value={[activeId, setActiveId]}>
                            <Accordion defaultActiveKey={activeId}>
                                {
                                    (activeLevel1Index >= 0) ? (
                                        cateData.level1Array[activeLevel1Index].level2Array.map((lvl2item, index) => {
                                            return (
                                                <div className='DialogLargeAccItem' key={"key" + index}>
                                                    <CustomToggle eventKey={index}>
                                                        <div className='DialogLargeAccHeaderTitle'>{lvl2item.meta.metavalstr}</div>
                                                        <div className='DialogLargeAccHeaderSubTitle'></div>
                                                    </CustomToggle>
                                                    <Accordion.Collapse eventKey={index}>
                                                        <>
                                                            {
                                                                cateData.level1Array[activeLevel1Index]
                                                                    .level2Array[index]
                                                                    .productArray.map((pdtitem, index2) => {
                                                                        return (
                                                                            <div
                                                                                className={(pdtitem.productDisplay.dpid === activeProductDisplay.dpid) ? "DialogLargeAccProductCellActive" : "DialogLargeAccProductCell"}
                                                                                key={index2}
                                                                                onClick={() => onProductCellClick(pdtitem)} >
                                                                                <input type='checkbox' className='DialogLargeCheckBox'
                                                                                    onChange={(ev) => onCheckBoxChanged(ev, pdtitem)}
                                                                                    checked={isProductInCurrGroup(pdtitem.displayid)}
                                                                                />
                                                                                <div className='DialogLargeAccPCH1'>{pdtitem.productDisplay.productname}</div>
                                                                                <div className='DialogLargeAccPCH2'>{pdtitem.productDisplay.subtitle}</div>
                                                                            </div>
                                                                        )
                                                                    })
                                                            }
                                                        </>
                                                    </Accordion.Collapse>
                                                </div>
                                            )
                                        })

                                    ) : ""
                                }
                            </Accordion>
                        </ActiveIdContext.Provider>

                    </div>

                    {/* detail detail detail detail */}
                    <div className='DialogLargeDetailView'>
                        {/* wrapper  */}
                        {(activeProductDisplay.type==='us')?<><div><Button variant="danger" size='sm' style={{float:'right',width:'120px',margin:'4px'}} onClick={()=>onDeleteUserScriptClick(activeProductDisplay)}>删除脚本</Button></div><div style={{clear:'both'}}></div></>:""}
                        {(detailHtmlText !== '') ? <div dangerouslySetInnerHTML={{ __html: detailHtmlText }}></div> : ""}
                        {(detailScriptText !== "") ? <Highlight className='javascript'>{detailScriptText}</Highlight> : ""}
                    </div>
                </div>
            </Modal.Body>
        </Modal>
    )
}

export default DialogLarge